package com.practice.xml.jaxb;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.practice.xml.Company;
import com.practice.xml.XmlProcessor;

public class JaxbXmlProcessor implements XmlProcessor {

	private JAXBContext context;
	
	private Marshaller marshaller;
	
	private Unmarshaller unmarshaller;
	
	public JaxbXmlProcessor() {
		try {
			context = JAXBContext.newInstance(JaxbCompany.class);
			marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			unmarshaller = context.createUnmarshaller();	
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void createXml(Company company, String filePath) {
		JaxbCompany jaxbCompany = new JaxbCompany(company);
		
		List<JaxbWorker> workers = new ArrayList<>();
		
		JaxbWorker worker = new JaxbWorker();
		worker.setName("Leonardo");
		worker.setSex(true);
		worker.setAge(30);
		worker.setDivision("Development");
		
		workers.add(worker);
		jaxbCompany.setWorkers(workers);
		
		try {
			OutputStream output = new FileOutputStream(filePath);
			marshaller.marshal(jaxbCompany, output);
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (JAXBException ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public Company parseXml(String filePath) {
		JaxbCompany jaxbCompany = null;
		try {
			InputStream input = new FileInputStream(filePath);
			jaxbCompany = (JaxbCompany) unmarshaller.unmarshal(input);
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (JAXBException ex) {
			ex.printStackTrace();
		}
		
		return jaxbCompany.toCompany();
	}

}
